import re
import time

import pandas as pd
import numpy as np
import paramiko
import netmiko


#下发指令创建OSPF，测试是否可以ping通，测试时延、抖动
#故障处理：ping测试，trace，查看接口状态，协议配置，
# 网络抓包、分析抓包文件内容





def ssh(host_dir)
    ssh=paramiko.SSHClient()
    # 自动添加未知的服务器密钥及策略
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=,port=22,username=,password=,)

#ssh下发指令,
# # 方法1--exec_command，需要服务器支持
# # 将服务器执行完的结果一次性返回给你
# # stdout 为正确输出，stderr为错误输出，同时是有1个变量有值
# stdin, stdout, stderr=ssh.exec_command('ls -l')
# print(stdout.read().decode())
# result=(str(stdout.read(),encoding='utf-8'))
# print(result)

# 方法2--invoke_shell()：
# 将执行结果分批次返回，看到任务的执行情况，不会因为执行一个很长的脚本而不知道是否执行成功
def send_command(host_ip,commands):
    ssh=paramiko.SSHClient()
    # 自动添加未知的服务器密钥及策略
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host_ip,port=22,username=username,password=password)
    command_channel=ssh.invoke_shell()
    output={}
    output[host_ip]={}
    command_channel.send('terminal length 0'+'\n')
    time.sleep(1)
    result=command_channel.recv(9999).decode("utf-8")

    for i in range(0,len(commands)):
        command=commands.at[i,0]+'\n'
        command_channel.send(command)
        time.sleep(1)
        result = command_channel.recv(9999).decode("utf-8")
        print(result)
        output[host_ip][command]=pd.DataFrame(result)

    return output


host_ip_list=['129.60.161.169', '129.60.161.170']
port=22
username='zte'
password='zte'


commands = pd.read_csv('commands.csv', header=None)

ouput_all_host=[]
for i in range(0,len(host_ip_list)):
    ouput_all_host.append(send_command(host_ip_list[i], commands))

pd.DataFrame.from_dict(ouput_all_host)



# 创建 SFTPClient 对象
sftp=ssh.open_sftp()

sftp.put(localpath=,remotepath=)
sftp.get(remotepath=,localpath=)
sftp.listdir(path=“.”)   #列出远程目录的内容。

# mkdir() 在服务器上创建目录
# remove() 在服务器上删除目录
# rename() 在服务器上重命名目录
# stat() 查看服务器文件状态
# listdir() 列出服务器目录下的文件
# 关闭SFTP会话和SSH连接
sftp.close()
ssh.close()


# trans=paramiko.transport()
# paramiko.SFTPClient.from_transport(trans)


#批量执行
pool = ThreadPoolExecutor(self.workers)
task = []
task.append(pool.submit(self.ssh_client, data[0], data[1], user, passwd))




def batch_sftp_get(ip, remote_path, local_path, user=None, passwd=None):
    ssh = ssh_client(ip, user, passwd)
    sftp = ssh.open_sftp()
    pool = multiprocessing.Pool(5)
    for i in ip:
        pool.apply_async(sftp.get(), (i, remote_path, local_path))
    pool.close()
    pool.join()


def batch_sftp_put(ip, local_path, remote_path, user=None, passwd=None, auth='id_rsa'):
    pool = ThreadPoolExecutor(max_workers=10)
    task = [pool.submit(sftp_put, i, local_path, remote_path, user, passwd) for i in ip]
    for future in as_completed(task):
        future.result()













from netmiko import SSHDetect, Netmiko, ConnectHandler
dev = {
    'device_type': 'zte_zxros',
    'host':   '129.60.161.169',
    'username': 'zte',
    'password': 'zte',
    'port' : 22,          # optional, defaults to 22
}

# 创建一个Detect的对象，将参数赋值
guesser = SSHDetect(**dev)

# 调用autodetect ，进行device_type的自动判断，返回结果是一个最佳结果的字符串，这个字符串就是netmiko自动判断的device_type
# 无法判断的时候返回的是None
best_match = guesser.autodetect()

print('best_match is:{}'.format(best_match))

net_connect = ConnectHandler(**dev)

output = net_connect.send_command('show ip interface brief')
print(output)
#解析show ip interface brief
output1=output.split('\n')
output2=[re.split(r'\s+',x.strip()) for x in output1]
output_ip_interface=pd.DataFrame(output2[1:],columns=output2[0]) #output2必须要是单列表

output_ip_interface[output_ip_interface['Interface'] == 'xgei-0/2/0/3']
dowm_interface=output_ip_interface[output_ip_interface['Admin']=='down']['Interface']

config_commands=[]
for x in dowm_interface:
    config_commands.append('interface '+x )
    config_commands.append('no shutdown')
    config_commands.append('exit')


output = net_connect.send_config_set(config_commands)
print(output)

output = net_connect.send_command('show interface')

output = net_connect.send_command('show interface xgei-0/2/0/3')
print(output)


output = net_connect.send_command('show ip ospf interface')
print(output)

output = net_connect.send_command('show ip ospf neighbor detail')
print(output)
#解析show ip interface brief
output1=output.split('\n')
output2=[re.split(r'\s+',x.strip()) for x in output1]
output=pd.DataFrame(output2[1:],columns=output2[0]) #output2必须要是单列表







config_commands = [ 'logging buffered 20000',
                    'logging buffered 20010',
                    'no logging console' ]
output = net_connect.send_config_set(config_commands)
print(output)




connection = Netmiko(**device)
in_config_mode = connection.check_config_mode()
print('config mode is :{}'.format(in_config_mode))
# 方法1 进入config model 输入命令，确定expect的字符，可以是正则，保存
connection.config_mode()
connection.send_command('interface eth1/50',expect_string='.*#')
connection.send_command('description configed by netmiko',expect_string='.*#')
connection.save_config()


